package com.kitty.game.fight.service;

import com.kitty.common.model.Pos;
import com.kitty.common.utils.SpringUtils;
import com.kitty.common.utils.ConcurrentHashSet;
import com.kitty.game.ServerService;
import com.kitty.game.chat.message.RespMessage;
import com.kitty.game.config.NPC;
import com.kitty.game.enter.*;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.equip.service.EquipService;
import com.kitty.game.fight.bean.Fight;
import com.kitty.game.map.MapDataPool;
import com.kitty.game.map.model.GroupMapParam;
import com.kitty.game.map.service.MapService;
import com.kitty.game.party.service.PartyService;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.pet.service.PetService;
import com.kitty.game.role.message.RespAppear;
import com.kitty.game.role.message.RespPlayLightEffect;
import com.kitty.game.role.message.RespPlaySound;
import com.kitty.game.role.message.RespUpdateAppearance;
import com.kitty.game.role.model.Role;
import com.kitty.game.scene.SceneManager;
import com.kitty.game.team.model.Member;
import com.kitty.game.team.model.Team;
import com.kitty.game.team.service.TeamService;
import com.kitty.game.titleManage.entity.TitleDetailInfo;
import com.kitty.game.titleManage.service.TitleInfoService;
import com.kitty.game.utils.SenderUtils;
import com.kitty.listener.EventType;
import com.kitty.listener.annotation.EventHandler;
import com.kitty.listener.event.LogoutEvent;
import com.kitty.mina.message.Message;
import com.kitty.mina.message.MessagePusher;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Dao;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class BroadcastService {
   // Logger logger = LoggerFactory.getLogger(BroadcastService.class);
    @Autowired
    MapService mapService;
    @Autowired
    TeamService teamService;
    @Autowired
    ServerService serverService;
    @Autowired
    FightService fightService;
    @Autowired
    EquipService equipService;
    @Autowired
    PetService petService;
    @Autowired
    Dao dao;
@Autowired
    NewBroadcastService newBroadcastService;
    @EventHandler(value={EventType.LOGOUT})
    public void handleLogoutEvent(LogoutEvent logoutEvent) {
        Role role = logoutEvent.getRole();
        SceneManager.INSTANCE.leaveMap(role.getPos().getMapId(), role);
    }

    public void sendRumor(String notice, NutMap nutMap) {
        this.cacheObjectInfo(nutMap);
        NPC npc = this.mapService.getNpcByName("玉真子");
        RespMessage respMessage = new RespMessage();
        respMessage.setLineName(this.serverService.getServer().getSonName());
        respMessage.setMsg(notice);
        respMessage.setId(npc.getId());
        respMessage.setTypeName(npc.getName());
        respMessage.setTime(new Long(new Date().getTime() / 1000L).intValue());
        respMessage.setChannel((short)6);
        respMessage.setIcon((short)npc.getIcon());
        SenderUtils.brodCastMessage((Message)respMessage, (String)"npc");
    }

    private void cacheObjectInfo(NutMap nutMap) {
        if (nutMap != null) {
            String type = nutMap.getString("type");
            if (type.equals("equip")) {
                RoleEquip roleEquip = (RoleEquip)nutMap.getAs("equip", RoleEquip.class);
                String uuId = nutMap.getString("uuId");
                List list = this.equipService.transferList(roleEquip.getFields());
                NutMap itemMap = NutMap.NEW();
                itemMap.setv("list", list);
                itemMap.setv("type", "道具");
                SpringUtils.getChatService().addChatCache(uuId, itemMap);
            } else if (type.equals("pet")) {
                Pet pet = (Pet)nutMap.getAs("pet", Pet.class);
                String uuId = nutMap.getString("uuId");
                ArrayList list = new ArrayList(pet.getAllFields());
                NutMap itemMap = NutMap.NEW();
                itemMap.setv("list", list);
                itemMap.setv("type", "宠物");
                SpringUtils.getChatService().addChatCache(uuId, itemMap);
            }
        }
    }

    public Message getPetAppear(Role role) {
        Pet pet = role.getPetBox().getPetByPetId(role.getFollowPetId());
        if (pet == null) {
            return null;
        }
        Pos pos = role.getPos();
        RespAppear respAppear = new RespAppear();
        respAppear.setRoleId(pet.getId());
        respAppear.setPosX(pos.getX());
        respAppear.setPosY(pos.getY());
        respAppear.setDir((short)pos.getDir());
        respAppear.setStatus((int)pet.getIcon());
        respAppear.setPortrait((int)pet.getIcon());
        respAppear.setIcon((int)pet.getIcon());
        respAppear.setRoleName(pet.getName());
        respAppear.setLevel(pet.getLevel());
        respAppear.setSpecial_icon(pet.getSpecial_icon());
        respAppear.setType((short)Short.MIN_VALUE);
        respAppear.setOrg_icon((int)pet.getIcon());
        respAppear.setLeaderId(role.getRoleId());
        respAppear.setSub_type(0);
        respAppear.setGid(pet.getGid());
        respAppear.setWeaponId(0);
        return respAppear;
    }

    public void sendSoundEffect(Role role) {
        RespPlayLightEffect effect = new RespPlayLightEffect();
        effect.setRoleId(role.getRoleId());
        effect.setEffectIcon(6071);
        RespPlaySound sound = new RespPlaySound("bianshen");
        SceneManager.INSTANCE.sendMessages(role, new Message[]{sound, effect});
    }

    public void sendUpdateAppear(Role role) {
        SceneManager.INSTANCE.sendMessages(role, new Message[]{this.getUpdateAppear(role)});
    }

    public void updateAppearance(Role role) {
        Message appear = this.getUpdateAppear(role);
        MessagePusher.pushMessage((Role)role, (Message)appear);
    }
    public void update_zhanli(Role role) { ////可以在此处做成为判断
    }



    public void sendAppear(Role role) {
        Message petAppear = this.getPetAppear(role);
        Message titleInfo = this.getTitleInfo(role);
        Message respAppear = this.getAppear(role);
        MessagePusher.pushMessage((Role)role, (Message)respAppear);
        MessagePusher.pushMessage((Role)role, (Message)titleInfo);
        MessagePusher.pushMessage((Role)role, (Message)petAppear);

    }

    public void updateAppearance(Role role, Role appearRole) {
        if (appearRole == null) {
            return;
        }
        Message appear = this.getUpdateAppear(appearRole);
        MessagePusher.pushMessage((Role)role, (Message)appear);
    }

    public Message getUpdateAppear(Role role) {

        Team team;
        int roleIcon = role.getRoleIcon();
        if(role.getTask().getAcceptedTaskLists().contains(2500)
                        || role.getTask().getAcceptedTaskLists().contains(2501)
                        || role.getTask().getAcceptedTaskLists().contains(2502)){

            roleIcon =  51001;
        }else{
            roleIcon = mapService.heroIcon(role.getGender(), role.getPolar());
        }

        RespUpdateAppearance respUpdateAppearance = new RespUpdateAppearance();
        if(roleIcon == 51001){
            respUpdateAppearance.setSpecial_icon(0);
            //respUpdateAppearance.setPortrait( role.getRoleIcon());
        }
        else{
            respUpdateAppearance.setSpecial_icon(role.getFasionIcon() != 0 ? role.getFasionIcon() : role.getShapePen() != null ? role.getShapePen().getIcon() : role.getChangeCard() != null ? role.getChangeCard().getIcon() : 0);
            //respUpdateAppearance.setPortrait(role.getShapePen() != null ? role.getShapePen().getIcon() : role.getChangeCard() != null ? role.getChangeCard().getIcon() : role.getRoleIcon());
        }








        Pos position = role.getPos();

        int specialIcon = role.getFasionIcon() != 0 ? role.getFasionIcon() : (role.getShapePen() != null ? (int)role.getShapePen().getIcon() : (role.getChangeCard() != null ? role.getChangeCard().getIcon() : 0));
        //respUpdateAppearance.setSpecial_icon(specialIcon);
        respUpdateAppearance.setPortrait(role.getShapePen() != null ? role.getShapePen().getIcon() : (short) (role.getChangeCard() != null ? role.getChangeCard().getIcon() : (roleIcon &= 0xFFFF)));
        respUpdateAppearance.setRoleId(role.getRoleId());
        respUpdateAppearance.setPosX(position.getX());
        respUpdateAppearance.setPosY(position.getY());
        respUpdateAppearance.setDir((short)position.getDir());
        respUpdateAppearance.setStatus(roleIcon);
        respUpdateAppearance.setIcon(roleIcon);
        respUpdateAppearance.setRoleName(role.getName());
        respUpdateAppearance.setLevel(role.getLevel());
        respUpdateAppearance.setFamilyName(this.mapService.getMenPaiName(role.getPolar()));
        respUpdateAppearance.setGid(role.getGid());
        respUpdateAppearance.setPartyName(role.getPartyName());
        respUpdateAppearance.setTitle(role.getCurrTitle());
        respUpdateAppearance.setOrg_icon(roleIcon);
        //获取当前激活的称号
        String currTitle = role.getCurrTitle();
        List<Integer> list = new ArrayList<>();
        if(StringUtils.isNotEmpty(currTitle)){
            TitleDetailInfo titleDetailInfo = TitleInfoService.allMapByGroup.get(currTitle);
            if(titleDetailInfo != null){
                list.add(titleDetailInfo.getIcon());
            }
        }
        //list.add(9000);
        list.add(role.getEffectIcon());
        respUpdateAppearance.setLight_effect(list);
        respUpdateAppearance.setWeaponId(role.getWeaponIcon());
        respUpdateAppearance.setSuit_icon(role.getSuitId());
        respUpdateAppearance.setSuit_light_effect(role.getSuitLightId() <= 7000 || role.getSuitLightId() >= 7006 ? 0 : role.getSuitLightId());
        if (role.isCustom() && !Strings.isEmpty((CharSequence)role.getCustomFasion())) {
            respUpdateAppearance.setCustomFasion(role.getCustomFasion());
            respUpdateAppearance.setSuit_icon(0);
            if (role.getGender() == 1) {
                respUpdateAppearance.setSpecial_icon(61001);
            } else {
                respUpdateAppearance.setSpecial_icon(60001);
            }
        }
        if (role.isVip()) {
            respUpdateAppearance.setVipColor((byte)1);
        } else {
            respUpdateAppearance.setVipColor((byte)0);
        }
        if (role.getMountIcon() > 0 && roleIcon != 51001) {
            respUpdateAppearance.setMoveSpeed((byte)role.getMoveSpeed());
            if (!role.isHideMount()) {
                respUpdateAppearance.setPet_icon(role.getMountIcon());
                Pet pet = this.petService.getPetById(role.getMount(), role);
                if(pet != null){
                    // add tao: 这里需要重新获取骑乘宠物ID
                    int newPosture = petService.getMountPosture(role, pet);
                    // 这里务必要设置新的posture，否则可能导致进入新地图的时候，元婴外观不切换
                    role.setMountPosture(newPosture);
                    respUpdateAppearance.setMount_icon(newPosture);
                }
                // add:e
                if (pet != null && pet.getZhuru() == 1) {
                    respUpdateAppearance.setShare_mount_icon(31501);
                    respUpdateAppearance.getLight_effect().add(7011);
                }
            }
        }
        if ((team = this.teamService.getTeam(role.getRoleId())) != null) {
            respUpdateAppearance.setLeaderId(team.getLeaderRoleId());
        }
        respUpdateAppearance.setFlyUp(role.getChildInfo().getType());
        respUpdateAppearance.setFlyUpState(role.getChildInfo().getState());
        if (role.getChildInfo().getState() != 0 && specialIcon == 0) {
            if (role.getChildInfo().getState() == 1)
                specialIcon = 7008;
            else
                specialIcon = 7009;
            respUpdateAppearance.setSpecial_icon(specialIcon);
        }

        if (role.isHide != -1) {
            respUpdateAppearance.setIsHide((byte)role.isHide);
        }
        if (role.type != -1) {
            respUpdateAppearance.setType((short)role.type);
        }
        if (role.sub_type != -1) {
            respUpdateAppearance.setSub_type(role.sub_type);
        }
//        int duiBiaoIcon = role.getPropsStatus().getInt("duibiao_icon", 0);
//        respUpdateAppearance.setDuibiaoIcon((short)duiBiaoIcon);
        newBroadcastService.getFeiXingUpdateAppear(role,respUpdateAppearance);
        SpringUtils.getBean(PartyService.class).notifyicon(role);
        return respUpdateAppearance;
    }

    public Message getAppear(Role role) {
        Team team;
        int roleIcon = role.getRoleIcon();

        if(role.getTask().getAcceptedTaskLists().contains(2500)
                        || role.getTask().getAcceptedTaskLists().contains(2501)
                        || role.getTask().getAcceptedTaskLists().contains(2502)){
            roleIcon =  51001;
        }else{
            roleIcon = mapService.heroIcon(role.getGender(), role.getPolar());
        }
//        logger.error("roleIcon={}",roleIcon);
        RespAppear respAppear = new RespAppear();
        if(roleIcon == 51001){
            respAppear.setSpecial_icon(0);
            //respAppear.setPortrait( role.getRoleIcon());
        }
        else{
            respAppear.setSpecial_icon(role.getFasionIcon() != 0 ? role.getFasionIcon() : role.getShapePen() != null ? role.getShapePen().getIcon() : role.getChangeCard() != null ? role.getChangeCard().getIcon() : 0);
          //  respAppear.setPortrait(role.getShapePen() != null ? role.getShapePen().getIcon() : role.getChangeCard() != null ? role.getChangeCard().getIcon() : role.getRoleIcon());
        }



//        respAppear.setSpecial_icon(role.getFasionIcon() != 0 ? role.getFasionIcon() : (role.getShapePen() != null ? (int)role.getShapePen().getIcon() : (role.getChangeCard() != null ? role.getChangeCard().getIcon() : 0)));
       respAppear.setPortrait(role.getShapePen() != null ? role.getShapePen().getIcon() : (role.getChangeCard() != null ? role.getChangeCard().getIcon() : (roleIcon &= 0xFFFF)));
        respAppear.setRoleId(role.getRoleId());
        respAppear.setPosX(role.getPos().getX());
        respAppear.setPosY(role.getPos().getY());
        respAppear.setDir((short)role.getPos().getDir());
        respAppear.setStatus(roleIcon);
        respAppear.setIcon(roleIcon);
        respAppear.setRoleName(role.getName());
        respAppear.setLevel(role.getLevel());
        respAppear.setFamilyName(this.mapService.getMenPaiName(role.getPolar()));
        respAppear.setGid(role.getGid());
        respAppear.setPartyName(role.getPartyName());
        respAppear.setTitle(role.getCurrTitle());
        respAppear.setOrg_icon(roleIcon);
        //获取当前激活的称号
        String currTitle = role.getCurrTitle();
        List<Integer> list = new ArrayList<>();
        if(StringUtils.isNotEmpty(currTitle)){
            TitleDetailInfo titleDetailInfo = TitleInfoService.allMapByGroup.get(currTitle);
            if(titleDetailInfo != null){
                list.add(titleDetailInfo.getIcon());
            }
        }
        //list.add(9000);
        list.add(role.getEffectIcon());
        respAppear.setLight_effect(list);
        respAppear.setWeaponId(role.getWeaponIcon());
        respAppear.setSuit_icon(role.getSuitId());
        respAppear.setSuit_light_effect(role.getSuitLightId() <= 7000 || role.getSuitLightId() >= 7006 ? 0 : role.getSuitLightId());
        if (role.isCustom() && !Strings.isEmpty((CharSequence)role.getCustomFasion())) {
            respAppear.setCustomFasion(role.getCustomFasion());
            respAppear.setSuit_icon(0);
            if (role.getGender() == 1) {
                respAppear.setSpecial_icon(61001);
            } else {
                respAppear.setSpecial_icon(60001);
            }
        }
        if (role.isVip()) {
            respAppear.setVipColor((byte)1);
        } else {
            respAppear.setVipColor((byte)0);
        }
        if (role.getMountIcon() > 0 && roleIcon != 51001) {
            respAppear.setMoveSpeed((byte)role.getMoveSpeed());
            if (!role.isHideMount()) {
                respAppear.setPet_icon(role.getMountIcon());
                respAppear.setMount_icon(role.getMountPosture());
                Pet pet = this.petService.getPetById(role.getMount(), role);
                if (pet != null && pet.getZhuru() == 1) {
                    respAppear.setShare_mount_icon(31501);
                    respAppear.getLight_effect().add(7011);
                }
            }
        }
        if ((team = this.teamService.getTeam(role.getRoleId())) != null) {
            respAppear.setLeaderId(team.getLeaderRoleId());
        }
        respAppear.setFlyUp(role.getChildInfo().getType());
        respAppear.setFlyUpState(role.getChildInfo().getState());
        if (role.isHide != -1) {
            respAppear.setIsHide((byte)role.isHide);
        }
        if (role.type != -1) {
            respAppear.setType((short)role.type);
        }
        if (role.sub_type != -1) {
            respAppear.setSub_type(role.sub_type);
        }
//        int duiBiaoIcon = role.getPropsStatus().getInt("duibiao_icon", 0);
//        respAppear.setTy((short)duiBiaoIcon);
        newBroadcastService.getFeiXingAppear(role,respAppear);
        SpringUtils.getBean(PartyService.class).notifyicon(role);
        return respAppear;
    }

    public void sendLocalMessage(Role role, Message message) {
        SceneManager.INSTANCE.sendMessages(role, new Message[]{message});
    }

    public void sendTitleInfo(Role role) {
        SceneManager.INSTANCE.sendMessages(role, new Message[]{this.getTitleInfo(role)});
    }

    public Message getDisAppear(int petId, int type) {
        if (petId <= 0) {
            return null;
        }
        RespDisappear respDisappear = new RespDisappear();
        respDisappear.setId(petId);
        respDisappear.setType((short)type);
        return respDisappear;
    }

    public Message getDisAppear(Role meRole) {
        return this.getDisAppear(meRole.getRoleId(), 1);
    }

    public Message getTitleInfo(Role role) {
        Team team = this.teamService.getTeam(role.getRoleId());
        Fight fight = this.fightService.getFightByRoleId(role.getRoleId());
        ArrayList<Byte> titleStatus = new ArrayList<Byte>();
        if (team != null) {
            titleStatus.add((byte)2);
            if (team.isLeader(role.getRoleId())) {
                if (team.getList().size() == 5) {
                    titleStatus.add((byte)4);
                } else {
                    titleStatus.add((byte)3);
                }
            } else {
                for (Member member : team.getList()) {
                    if (member.getRoleId() != role.getRoleId() || !member.isInTeam()) continue;
                    titleStatus.add((byte)5);
                    break;
                }
            }
        }
        if (fight != null && !fight.isOver()) {
            titleStatus.add((byte)1);
        }
        if (role.getPkInfoBox().isRedName()) {
            titleStatus.add((byte)7);
        }
        RespTitle respTitle = new RespTitle();
        respTitle.setRoleId(role.getRoleId());
        respTitle.setList(titleStatus);
        return respTitle;
    }

    public Message getMovePacket(Role role) {
        RespPositionMove respPositionMove = new RespPositionMove();
        respPositionMove.setRoleId(role.getRoleId());
        respPositionMove.setX(role.getPos().getX());
        respPositionMove.setY(role.getPos().getY());
        respPositionMove.setDir(role.getPos().getDir());
        return respPositionMove;
    }

    public boolean inSameScene(Role role, Role otherRole) {
        if (role == null || otherRole == null) {
            return false;
        }
        if (role.getPos().getMapId() == 37000) {
            return otherRole.getPos().getMapId() == 37000 && role.getActivity().getRoleTowerData() != null && otherRole.getActivity().getRoleTowerData() != null && role.getActivity().getRoleTowerData().getCurrentLayer() == otherRole.getActivity().getRoleTowerData().getCurrentLayer();
        }
        if (MapDataPool.polarMaps.contains(role.getPos().getMapId())) {
            return role.getPolar() == otherRole.getPolar();
        }
        if (MapDataPool.MAP_KEY_GENERATERS.containsKey(role.getPos().getMapId())) {
            ConcurrentHashSet roleIds = SpringUtils.getMapService().getRoleIds(new GroupMapParam(role), role.getPos().getMapId());
            return roleIds != null && roleIds.contains(otherRole.getRoleId());
        }
        return role.getPos().getMapId() == otherRole.getPos().getMapId();
    }
}
